const app = getApp();
const Controller = require('../controllers/controllers.js').controller;
Page({
  data: {
    title:'搜索结果',
    inputValue:'',
    searchlists:[],
    page:1,
    pageSize:10,
    isEnd:false,
    remommendlists:[],
    remommendpage:1,
    remommendpageSize:10,
    remommendisEnd:false,
    focusbool:false,
    focuslists:[],
    focuspage:1,
    focuspageSize:10,
    focusisEnd:false

  },
  onLoad: function (options) {
    this.setData({
        inputValue: options.search || ''
    });
    this.searchlists()
    this.remommendlistS()
  },

  onReady() {
      this.Dialog = this.selectComponent('#Dialog');
  },
  searchlists(){
    Controller.audioList({
      keyword:this.data.inputValue,
      page:this.data.focuspage,
      pageSize:this.data.focuspageSize
    }).then(res => {
      if(res.data.baseData.list.length>0){
        for(let item of res.data.baseData.list){
          if(item.title){
          item.title=item.title.replace(this.data.inputValue,"<span class='orange'>"+this.data.inputValue+"</span>");
          }
          if(item.desc){
          item.desc=item.desc.replace(this.data.inputValue,"<span class='orange'>"+this.data.inputValue+"</span>");
          }
        }
        this.setData({
          searchlists:this.data.searchlists.concat(res.data.baseData.list)
        })
        if(res.data.baseData.lastPage){
          this.setData({
            isEnd:true
          })
        }
      }
    })
  },
  remommendlistS(){
    Controller.audioList({
      isRecommend:1,
      page:this.data.remommendpage,
      pageSize:this.data.remommendpageSize
    }).then(res => {
      if(res.data.baseData.list.length>0){
        this.setData({
          remommendlists:this.data.remommendlists.concat(res.data.baseData.list)
        })
        if(res.data.baseData.lastPage){
          this.setData({
            remommendisEnd:true
          })
        }
      }
    })
  },
  refesh(){
    this.setData({
      remommendlists:[],
      remommendpage:1,
      remommendpageSize:10,
      remommendisEnd:false,
    })
    this.remommendlistS()
  },

  onReachBottom() {
    if (this.data.isEnd) {
      return;
    } else {
      this.setData({
          page: this.data.page + 1,
      });
      this.searchlists()
    }
    if (this.data.remommendisEnd) {
      return;
    } else {
      this.setData({
          remommendpage: this.data.remommendpage + 1,
      });
      this.remommendlistS()
    }
  },
  playall(e) {
    var index=0;
    var type=e.currentTarget.dataset.type
    if(e.currentTarget.dataset.index){
      index=e.currentTarget.dataset.index
    }
    app.globalData.currentIndex=index
    if(type && type==1){
      app.globalData.songlist=this.data.remommendlists
    }else{
      var lists=this.data.searchlists;
      for(let item of lists){
        if(item.title){
          item.title=item.title.replace("<span class='orange'>","");
          item.title=item.title.replace("</span>","");
        }
        if(item.desc){
          item.desc=item.desc.replace("<span class='orange'>","");
          item.desc=item.desc.replace("</span>","");
        }
      }
      app.globalData.songlist=lists
    }


    wx.navigateTo({
      url: "/pages/Playing/Playing?keyword=" + this.data.inputValue
    })
  },
  searchSubmit(e){
    console.log(e)
    let _SearchValue = e.target.dataset.search;
    let localStorageValue = [];

    if (_SearchValue != '') {

        //添加搜索历史记录
        //调用API从本地缓存中获取数据
        localStorageValue = wx.getStorageSync('searchData') || [];

        let tempSearchData = [];
        //过滤历史列表中相同的搜索记录
        for (let item of localStorageValue) {
            if (item != _SearchValue) {
                tempSearchData.push(item);
            }
        }
        //添加搜索文本进历史记录
        tempSearchData.push(_SearchValue);
        //保存至从本地缓存
        wx.setStorageSync('searchData', tempSearchData);
        this.setData({
          searchlists:[],
          page:1,
          pageSize:10,
          isEnd:false,
          remommendlists:[],
          remommendpage:1,
          remommendpageSize:10,
          remommendisEnd:false
        })
        this.searchlists()
    }
  },
  bindInput(e){
    var value=e.detail.value || ''
    console.log(value)
    if(value){
      this.setData({
        inputValue: value
      })
    }
  },
  mvlook(e){
    wx.navigateTo({
      url: '/pages/weixinlink/weixinlink?url='+e.currentTarget.dataset.url
    })
  },
  mvmin(e){
    wx.navigateToMiniProgram({
      appId: e.currentTarget.dataset.id,
      path: e.currentTarget.dataset.path,
      extraData: {},
      envVersion: 'release',
      success(res) {
        // 打开成功
      }
    })
  },
  //初始化
  _init() {
    let currentIndex = app.globalData.currentIndex || 0;
    let songslist = (app.globalData.songlist.length && app.globalData.songlist)
    let currentSong = app.globalData.songlist[app.globalData.currentIndex] || (songslist && songslist[app.globalData.currentIndex])
    let duration = currentSong && currentSong.duration
    this.setData({
      currentSong: currentSong,
      duration: duration,
      songslist: songslist,
      currentIndex: currentIndex
    })
    this._getPlayUrl(currentSong)
  },
  // 获取播放地址
  _getPlayUrl(currentSong) {
    const _this = this
    console.log('currentSong',currentSong)
    if (currentSong && currentSong.audioUrl) {
      _this._createAudio(currentSong)
    } else {
      const manage = wx.getBackgroundAudioManager()
      manage.stop()
      wx.showToast({
        title: '本歌曲暂时不能播放。请切换下一首',
        icon: 'none'
      })
    }
  },
  // 创建播放器
  _createAudio(currentSong) {
    wx.playBackgroundAudio({
      dataUrl: currentSong.audioUrl,
      title: currentSong.title,
      coverImgUrl: currentSong.imgUrl
    })
    // 监听音乐播放。
    wx.onBackgroundAudioPlay(() => {
      this.setData({
        play: 2
      })
      app.currentSong=currentSong
      app.play(currentSong.id)
    })
    // 监听音乐暂停。
    wx.onBackgroundAudioPause(() => {
      this.setData({
        play: 1
      })
      // 更新收听时长接口
      Controller.uploadListenTimes({
        seconds: parseInt(this.data.currentTime)
      })
      .then(res => {

      })
    })
    // 监听音乐停止。
    wx.onBackgroundAudioStop(() => {
      if (this.data.playMod === SINGLE_CYCLE_MOD) {
        this._init()
        return
      }
      // 更新收听时长接口
      Controller.uploadListenTimes({
        seconds: parseInt(this.data.currentTime)
      })
      .then(res => {

      })
      this.next()
    })
  },
  onTimeUpdate(time){
    // 监听播放拿取播放进度
    const manage = wx.getBackgroundAudioManager()
    if(time){
      manage.seek(time);
    }
    manage.onTimeUpdate(() => {
      const currentTime = manage.currentTime;
      const duration=manage.duration
      this.setData({
        currentTime: this._formatTime(currentTime),
        duration:this._formatTime(duration),
        percent: currentTime / duration*100
      })
    })
  },
  prev() {
    app.globalData.currentIndex = this.getNextIndex(false)
    this._init()
  },
  next() {
    app.globalData.currentIndex = this.getNextIndex(true)
    this._init()
  },
  getNextIndex(nextFlag) {
    let ret,
        currentIndex = app.globalData.currentIndex,
        mod = this.data.playMod,
        len = this.data.songslist.length
    if (mod === RANDOM_MOD) {
      ret = randomNum(len)
    } else {
      if (nextFlag) {
        ret = currentIndex + 1 == len ? 0 : currentIndex + 1
      } else {
        ret = currentIndex - 1 < 0 ? len - 1 : currentIndex - 1
      }
    }
    return ret
  },
  togglePlaying(e) {
    wx.getBackgroundAudioPlayerState({
      success(res) {
        var status = res.status
        if (status == 1) {
          wx.pauseBackgroundAudio()
        } else {
          wx.playBackgroundAudio()
        }
      }
    })
  },
  onShareAppMessage: function (e) {
    // if (e.from == "button") {
      let obj = {
        title: '有氧FM·搜索结果',
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      return obj
    // }
  },
  onShareTimeline: function (e) {
    // if (e.from == "button") {
      let obj = {
        title: '有氧FM·搜索结果',
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      return obj
    // }
  },
})